<template>
  <el-upload
      :with-credentials="true"
      :action="dirName"
      ref="upload"
      class="upload-demo"
      :limit="limit"
      list-type="picture-card"
      accept=".png, .jpg"
      :on-success="picureUpLoadSuccess"
      :on-error="picureUpLoadFail"
      :on-remove="handleUploadRemove"
      :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview"
  >
    <template #trigger>
      <el-button type="primary"> 点击上传 </el-button>
    </template>
    <template #tip>
      <div class="el-upload__tip text-red">
        只能上传一张jpg/png格式的图片，图片大小不能超过2MB，且尺寸不能超过1500x1500像素
      </div>
    </template>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <el-image  :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup>
import {defineAsyncComponent, getCurrentInstance, ref} from "vue";
import {ElMessage, ElNotification} from "element-plus";

const props = defineProps({
  fileType: {
    type: String,
    default: ''
  },
  limit: {
    default: 1
  },
  attribute: {
    type: String,
    default: ''
  }
})
const {attribute} = props
const emits = defineEmits(["getFormPicValue"])
const {fileType} = props
const dirName = ref('')
const fileName = ref('')
const tpmc = ref('')
let pic = ref('')
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const beforeUpload = (file) =>{
  return new Promise((resolve, reject) => {
    // 在上传之前获取文件名称
    fileName.value = file.name
    console.log('文件名称为：', file.name)
    dirName.value = `http://localhost:8080/tea/${fileType}/image`
    console.log(dirName.value)

    tpmc.value = fileName.value
    // resolve(true)
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      let img = new Image()
      img.src = reader.result
      img.onload = () => {
        const width = img.width
        const height = img.height
        console.log(`图片尺寸为：${width} x ${height}`)
        // 在这里根据图片尺寸进行判断，例如：
        if (width > 1500 || height > 1500) {
          ElMessage({
            message: "图片尺寸过大，请重新上传！",
            type: 'warning',
            duration: 1500
          })
          reject(false)
        } else {
          resolve(true)
        }
      }
    }
  })
}
const picureUpLoadSuccess = (response)=> {
  pic.value = `data:image/png;image/jpeg;base64,${response.data}`
  emits("getFormPicValue", {pic: pic.value, tpmc: tpmc.value, attr: attribute,})
  ElNotification({
    message: "图片上传成功！",
    type: 'success',
    duration: 1500
  })
}
const picureUpLoadFail = (e)=> {
  tpmc.value = ''
  console.log(e)
  ElNotification({
    message: "图片上传失败~",
    type: 'error',
    duration: 1500
  })
}
const handleUploadRemove = (file, fileList) => {
  // 如果用户删除了上传的文件，清空数据中的存储路径
  // 在这里处理文件删除操作
  tpmc.value = ''
}
const handlePictureCardPreview = (uploadFile) => {
  console.log(uploadFile)
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
</script>

<style scoped>

</style>